
// 历史事件数据
const historicalEvents = [
  {
    id: 1,
    year: 1978,
    title: "十一届三中全会召开",
    description: "确立改革开放基本国策，中国进入社会主义现代化建设新时期",
    isPlaced: false
  },
  {
    id: 2,
    year: 1980,
    title: "深圳经济特区成立",
    description: "设立首批经济特区，开启对外开放窗口",
    isPlaced: false
  },
  {
    id: 3,
    year: 1984,
    title: "城市经济体制改革启动",
    description: "改革从农村扩展到城市，全面推进经济体制改革",
    isPlaced: false
  },
  {
    id: 4,
    year: 1992,
    title: "邓小平南方谈话",
    description: "确立社会主义市场经济体制改革目标，改革开放进入新阶段",
    isPlaced: false
  },
  {
    id: 5,
    year: 1997,
    title: "香港回归祖国",
    description: "一国两制成功实践，祖国统一大业迈出重要一步",
    isPlaced: false
  },
  {
    id: 6,
    year: 2001,
    title: "中国加入世界贸易组织",
    description: "正式成为WTO成员，全面融入世界经济体系",
    isPlaced: false
  },
  {
    id: 7,
    year: 2008,
    title: "北京奥运会成功举办",
    description: "展示改革开放成果，提升国家形象和民族自信心",
    isPlaced: false
  },
  {
    id: 8,
    year: 2010,
    title: "上海世博会召开",
    description: "展示城市文明成果，促进国际交流与合作",
    isPlaced: false
  },
  {
    id: 9,
    year: 2013,
    title: "一带一路倡议提出",
    description: "构建人类命运共同体，推进全球互联互通",
    isPlaced: false
  },
  {
    id: 10,
    year: 2017,
    title: "党的十九大召开",
    description: "确立习近平新时代中国特色社会主义思想，开启全面建设社会主义现代化国家新征程",
    isPlaced: false
  },
  {
    id: 11,
    year: 2020,
    title: "脱贫攻坚战取得全面胜利",
    description: "现行标准下9899万农村贫困人口全部脱贫，全面建成小康社会",
    isPlaced: false
  },
  {
    id: 12,
    year: 2021,
    title: "建党百年庆典",
    description: "庆祝中国共产党成立100周年，宣告全面建成小康社会",
    isPlaced: false
  }
];

// 游戏状态
let gameState = {
  shuffledEvents: [],
  placedEvents: new Map(),
  correctPlacements: 0,
  totalEvents: historicalEvents.length
};

// DOM 元素
let cardsContainer, timelineContainer, accuracySpan, completedSpan, totalSpan;

// 初始化游戏
function initGame() {
  // 获取 DOM 元素
  cardsContainer = document.getElementById('cardsContainer');
  timelineContainer = document.getElementById('timelineContainer');
  accuracySpan = document.getElementById('accuracy');
  completedSpan = document.getElementById('completed');
  totalSpan = document.getElementById('total');

  // 重置游戏状态
  gameState.shuffledEvents = shuffleArray([...historicalEvents]);
  gameState.placedEvents.clear();
  gameState.correctPlacements = 0;

  // 更新统计信息
  totalSpan.textContent = gameState.totalEvents;
  updateStats();

  // 渲染界面
  renderCards();
  renderTimeline();
}

// 数组随机排序
function shuffleArray(array) {
  const shuffled = [...array];
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled;
}

// 渲染卡片
function renderCards() {
  cardsContainer.innerHTML = '';
  
  gameState.shuffledEvents.forEach(event => {
    if (!event.isPlaced) {
      const cardElement = createCardElement(event);
      cardsContainer.appendChild(cardElement);
    }
  });
}

// 创建卡片元素
function createCardElement(event) {
  const card = document.createElement('div');
  card.className = 'event-card';
  card.draggable = true;
  card.dataset.eventId = event.id;
  card.dataset.year = event.year;
  
  card.innerHTML = `
    <div class="card-title">${event.title}</div>
    <div class="card-desc">${event.description}</div>
  `;

  // 添加拖拽事件监听器
  card.addEventListener('dragstart', handleDragStart);
  card.addEventListener('dragend', handleDragEnd);

  return card;
}

// 渲染时间轴
function renderTimeline() {
  timelineContainer.innerHTML = '';

  // 按年份排序事件
  const sortedEvents = [...historicalEvents].sort((a, b) => a.year - b.year);
  
  sortedEvents.forEach(event => {
    const timelineItem = createTimelineItem(event);
    timelineContainer.appendChild(timelineItem);
  });
}

// 创建时间轴项目
function createTimelineItem(event) {
  const item = document.createElement('div');
  item.className = 'timeline-item';
  item.dataset.year = event.year;

  const content = document.createElement('div');
  content.className = 'timeline-content';
  content.dataset.year = event.year;

  // 添加拖放事件监听器
  content.addEventListener('dragover', handleDragOver);
  content.addEventListener('drop', handleDrop);
  content.addEventListener('dragleave', handleDragLeave);

  item.innerHTML = `
    <div class="timeline-year">${event.year}年</div>
  `;

  // 检查是否已有放置的卡片
  if (gameState.placedEvents.has(event.year)) {
    const placedEvent = gameState.placedEvents.get(event.year);
    const placedCard = createCardElement(placedEvent);
    placedCard.classList.add('placed-card');
    placedCard.draggable = false;
    content.appendChild(placedCard);
  } else {
    content.innerHTML += `
      <div style="color: #999; font-size: 14px; text-align: center; padding: 20px 0;">
        将对应事件拖拽到此处
      </div>
    `;
  }

  item.appendChild(content);
  return item;
}

// 拖拽开始
function handleDragStart(e) {
  e.dataTransfer.effectAllowed = 'move';
  e.dataTransfer.setData('text/html', e.target.innerHTML);
  e.dataTransfer.setData('eventId', e.target.dataset.eventId);
  e.dataTransfer.setData('year', e.target.dataset.year);
  
  e.target.classList.add('dragging');
}

// 拖拽结束
function handleDragEnd(e) {
  e.target.classList.remove('dragging');
}

// 拖拽悬停
function handleDragOver(e) {
  e.preventDefault();
  e.dataTransfer.dropEffect = 'move';
  
  e.currentTarget.classList.add('drag-over');
}

// 拖拽离开
function handleDragLeave(e) {
  e.currentTarget.classList.remove('drag-over');
}

// 放置
function handleDrop(e) {
  e.preventDefault();
  e.currentTarget.classList.remove('drag-over');

  const eventId = parseInt(e.dataTransfer.getData('eventId'));
  const cardYear = parseInt(e.dataTransfer.getData('year'));
  const targetYear = parseInt(e.currentTarget.dataset.year);

  // 检查是否已经放置了其他事件
  if (gameState.placedEvents.has(targetYear)) {
    showMessage('该位置已有事件，请先移除或选择其他位置', 'warning');
    return;
  }

  // 找到对应的事件
  const event = gameState.shuffledEvents.find(evt => evt.id === eventId);
  if (!event) return;

  // 放置事件
  if (cardYear === targetYear) {
    // 正确放置
    event.isPlaced = true;
    gameState.placedEvents.set(targetYear, event);
    gameState.correctPlacements++;
    
    e.currentTarget.classList.add('correct');
    showMessage('正确！事件已放置到正确位置', 'success');
  } else {
    // 错误放置
    e.currentTarget.classList.add('incorrect');
    showMessage('位置错误，请重新尝试', 'error');
    
    // 1.5秒后移除错误样式
    setTimeout(() => {
      e.currentTarget.classList.remove('incorrect');
    }, 1500);
    
    return;
  }

  // 更新界面
  renderCards();
  renderTimeline();
  updateStats();

  // 检查游戏是否完成
  if (gameState.correctPlacements === gameState.totalEvents) {
    setTimeout(() => {
      showMessage('🎉 恭喜！您已成功完成所有事件的排序！', 'success');
    }, 500);
  }
}

// 更新统计信息
function updateStats() {
  const accuracy = gameState.totalEvents > 0 
    ? Math.round((gameState.correctPlacements / gameState.totalEvents) * 100)
    : 0;
  
  accuracySpan.textContent = `${accuracy}%`;
  completedSpan.textContent = gameState.correctPlacements;
}

// 显示消息
function showMessage(message, type) {
  // 创建消息元素
  const messageEl = document.createElement('div');
  messageEl.className = `message message-${type}`;
  messageEl.textContent = message;
  
  // 添加样式
  messageEl.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 12px 20px;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 500;
    z-index: 1000;
    animation: slideInRight 0.3s ease-out;
  `;
  
  // 根据类型设置颜色
  const colors = {
    success: { bg: '#f6ffed', border: '#b7eb8f', color: '#52c41a' },
    error: { bg: '#fff1f0', border: '#ffa39e', color: '#ff4d4f' },
    warning: { bg: '#fffbe6', border: '#ffe58f', color: '#faad14' }
  };
  
  const color = colors[type] || colors.success;
  messageEl.style.backgroundColor = color.bg;
  messageEl.style.border = `1px solid ${color.border}`;
  messageEl.style.color = color.color;
  
  document.body.appendChild(messageEl);
  
  // 3秒后自动移除
  setTimeout(() => {
    messageEl.style.animation = 'slideOutRight 0.3s ease-in';
    setTimeout(() => {
      if (messageEl.parentNode) {
        messageEl.parentNode.removeChild(messageEl);
      }
    }, 300);
  }, 3000);
}

// 重置游戏
function resetGame() {
  // 重置所有事件状态
  historicalEvents.forEach(event => {
    event.isPlaced = false;
  });
  
  // 重新初始化
  initGame();
  showMessage('游戏已重置，请重新开始', 'success');
}

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
  @keyframes slideInRight {
    from {
      transform: translateX(100%);
      opacity: 0;
    }
    to {
      transform: translateX(0);
      opacity: 1;
    }
  }
  
  @keyframes slideOutRight {
    from {
      transform: translateX(0);
      opacity: 1;
    }
    to {
      transform: translateX(100%);
      opacity: 0;
    }
  }
`;
document.head.appendChild(style);

// 页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', initGame);
